package com.czq.controllor;


import com.czq.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

@RestController
@Slf4j
@RequestMapping("/common")
public class FileControllor {

    @Value("${waimai.path}")
    private  String path;

    @PostMapping("/upload")
    public Result<String>  upload(MultipartFile file) throws IOException {


//        String name = file.getName();
//        System.out.println(name);

        File filee = new File(path);
        if (!filee.exists()){
            filee.mkdirs();
        }
        String originalFilename = file.getOriginalFilename();
        String jdg = originalFilename.substring(originalFilename.lastIndexOf("."));
        String filename = UUID.randomUUID().toString()+jdg;

//        System.out.println(originalFilename);
        file.transferTo(new File(path+filename));
        return Result.success(filename);
    }

    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) throws IOException {
        FileInputStream fileInputStream=new FileInputStream(new File(path+name));

        int len=0;
        byte[] bytes=new byte[1024];
        ServletOutputStream outputStream = response.getOutputStream();
        while (   (len=fileInputStream.read(bytes)) != -1 ) {
            outputStream.write(bytes,0,len);
            outputStream.flush();
        }
        fileInputStream.close();
        outputStream.close();


    }
}
